const express = require("express");
const pool = require("../pool.js");

const kindRouter = express.Router();
module.exports = kindRouter;

// 查询整个表
kindRouter.get("/findAll", (req, res,next) => {
  var page = req.query.page || 1;
  const pagesize = 10;
  var offset = (page - 1) * pagesize;
  var sql = `select count(kid) as count from kind`;
  pool.query(sql, (err, r) => {
    if (err) {
      next(err);
      return;
    }
    let pagecount = Math.ceil(r[0].count / pagesize);
    var sql = `select * from kind limit ?,?`;
    pool.query(sql, [offset, pagesize], (err, r, next) => {
      if (err) {
        next(err);
        return;
      }
      res.send({ code: 200, data: r, pagecount });
    });
  });
});
// 根据种类名称查
kindRouter.get("/find", (req, res,next) => {
  var kname = req.query.kname;
  var sql = `select * from kind where kname=?`;
  pool.query(sql, [kname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      res.send({ code: 200, data: r, msg: "ok" });
    } else {
      res.send({ code: 201, msg: "找不到该名称" });
    }
  });
});
// 新增种类
kindRouter.post("/insert", (req, res,next) => {
  var kname = req.body.kname;
  var kdetail = req.body.kdetail;
  var knotice = req.body.knotice;
  if (
    kname == "" ||
    kname == undefined ||
    kdetail == "" ||
    kname == undefined
  ) {
    res.send({ code: 202, msg: "输入不能为空" });
    return;
  }
  var sql1 = `select kid from kind where kname=?`;
  pool.query(sql1, [kname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (r.length != 0) {
      res.send({ code: 201, msg: "种类名称已存在" });
    } else {
      var sql2 = `insert into kind values(null,?,?,?)`;
      pool.query(sql2, [kname, kdetail, knotice], (err, r) => {
        if (err) {
          next(err);
          return;
        }
        res.send({ code: 200, msg: "插入成功" });
      });
    }
  });
});
// 删除种类
kindRouter.delete("/delete", (req, res,next) => {
  var kname = req.query.kname;
  var sql = `delete from kind where kname=?`;
  pool.query(sql, [kname], (err, r) => {
    if (err) {
      next(err);
      return;
    }
    if (!r.affectedRows) {
      res.send({ code: 201, msg: "删除失败，没有此类" });
    } else {
      res.send({ code: 200, msg: "删除成功" });
    }
  });
});
